package com.dmzc.stage3.Unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class Test4 {
    public static void main(String[] args) {
        //最大数组大小受限制
        //System.out.println(Integer.MAX_VALUE);
        //String [] arr=new String[Integer.MAX_VALUE-1988714520];
        long SUPER_SIZE = (long) Integer.MAX_VALUE * 2;
        SuperArray array = new SuperArray(SUPER_SIZE);
        System.out.println("Array size:" + array.size());
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            array.set((long) Integer.MAX_VALUE + i, (byte) 3);
            sum+=array.get((long)Integer.MAX_VALUE+i);
        }
        System.out.println("sum of 100 elements:"+sum);
    }

    private static Unsafe getUnsafe() {
        Unsafe unsafe = null;
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            unsafe = (Unsafe) f.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unsafe;
    }

    static class SuperArray {
        private final static int BYTE = 1;
        private long size;
        private long address;

        public SuperArray(long size) {
            this.size = size;
            address = getUnsafe().allocateMemory(size * BYTE);
        }

        public void set(long i, Byte value) {
            getUnsafe().putByte(address + i * BYTE, value);
        }

        public int get(long idx) {
            return getUnsafe().getByte(address + idx * BYTE);
        }

        public long size() {
            return size;
        }
    }
}
